package demo.comm;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import demo.controller.StatusController;

@RestControllerAdvice
public class MyControllerAdvice{
	
	private static final Logger log = LoggerFactory.getLogger(StatusController.class);

	@ExceptionHandler(value = Exception.class)
    public Map<String,Object> errorHandler(Exception e) {
		log.error("MyControllerAdvice.errorHandler", e);
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("Exception", e+"");
        
        return map;
    }
	
	@ExceptionHandler(value = RuntimeException.class)
    public Map<String,Object> runtimeExceptionHandler(Exception e) {
		log.error("MyControllerAdvice.runtimeExceptionHandler", e);
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("RuntimeException", e+"");
        
        return map;
    }
	
	@ExceptionHandler(value = Throwable.class)
    public Map<String,Object> throwableHandler(Exception e) {
		log.error("MyControllerAdvice.throwableHandler", e);
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("Throwable", e+"");
        
        return map;
    }
	
	@ExceptionHandler(value = Error.class)
    public Map<String,Object> errHandler(Exception e) {
		log.error("MyControllerAdvice.errHandler", e);
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("Error", e+"");
        
        return map;
    }
	
	
	
	@InitBinder
    public void globalInitBinder(WebDataBinder binder) {
		// org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.util.Date'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.util.Date] for value '2021-02-01'; nested exception is java.lang.IllegalArgumentException
        binder.addCustomFormatter(new DateFormatter("yyyy-MM-dd"));
    }
	
	@ModelAttribute(value = "globalMessage")
    public String globalModelAttribute() {
        System.out.println("globalModelAttribute set");
        
        
        return "globalMessage,"+LocalDateTime.now();
    }
	
	@ModelAttribute 
    public void globalModelAttributeBuild(Model model) {
        System.out.println("globalModelAttributeBuild run");
        model.addAttribute("globalModelAttribute2", "globalModelAttribute2-"+LocalDateTime.now());
        
    }

}